package org.apache.sad.core.framework.utils;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.rmi.RemoteException;

import javax.ejb.EJBException;

import org.springframework.remoting.RemoteAccessException;

import org.apache.sad.core.framework.exception.BaseException;

/**
 * Provides helper methods on exception handling.
 * 
 * @author Anup Dixit
 */
public class ExceptionUtil {
	/**
	 * Returns the root cause of a Throwable.
	 */
	public static Throwable getRootCause(Throwable t) {
		while ( t.getCause() != null ) {
			t = t.getCause();
		}
		return t;
	}
	
	/**
	 * Returns the root {@code BaseException}. If {@code BaseException} is not in the chain, then the actual root cause will be
	 * returned.
	 */
	public static Throwable getRootBaseException(Throwable t) {
		while ( !(t instanceof BaseException) && t.getCause() != null ) {
			t = t.getCause();
		}
		return t;
	}
	
	/**
	 * Used to unwrap exception thrown from ejb calls.
	 */
	public static Throwable unwrapEjbRemoteAccessException(Throwable e) {
		while ( e instanceof RemoteAccessException || e instanceof EJBException || e instanceof RemoteException ) {
			if ( e.getCause() != null ) {
				e = e.getCause();
			} else {
				break;
			}
		}
		return e;
	}
	
	
	/**
	 * Returns stack trace of a Throwable as string.
	 */
	public static String toStatckTrace(Throwable t) {
		StringWriter sw = new StringWriter();
		t.printStackTrace(new PrintWriter(sw));
		return sw.toString();
	}	
}
